'use strict';

angular.module('picasa', [])

  .constant('constants', {
    userId: '101263606183133134843',
    bigThumbSize: 512,
    littleThumbSize: 104
  })

  .service('picasaService', ['$http', '$q', 'picasaFactory', 'constants', function ($http, $q, picasaFactory, constants) {

    this.loadAlbums = function() {
      var albums = [];
      loadAlbumsPromise().then(function(data) {
        angular.forEach(data.feed.entry, function (album) {
          albums.push(picasaFactory.album.createModel(album));
        });
      });
      return albums;
    };

    function loadAlbumsPromise() {
      var d = $q.defer();
      $http.jsonp(picasaFactory.album.createURI(
          constants.userId,
          constants.bigThumbSize,
          constants.littleThumbSize)).success(function (data) {
        d.resolve(data);
      });
      return d.promise;
    }

  }])

  .factory('picasaFactory', function () {

    var getAlbumURI = function (user, bigThumbSize, littleThumbSize) {
      return 'http://picasaweb.google.com/data/feed/api/' +
        'user/' + user +
        '?alt=' + 'json' +
        '&access=visible' +
        '&v=2' +
        '&kind=' + 'album' +
        '&hl=' + 'en_US' +
        '&fields=' + 'entry(media:group,id,gphoto:id,gphoto:numphotos)' +
        '&thumbsize=' + bigThumbSize + ',' + littleThumbSize +
        '&callback=JSON_CALLBACK';
    };

    function Album(feedEntry) {
      var self = this;
      self.id = feedEntry.gphoto$id.$t;
      self.numberOfPhotos = feedEntry.gphoto$numphotos.$t;
      self.title = feedEntry.media$group.media$title.$t;
      self.bigThumbURL = '';
      self.littleThumbURL = '';
      angular.forEach(feedEntry.media$group.media$thumbnail, function (thumbnail) {
        if (thumbnail.height === 512) {
          self.bigThumbURL = thumbnail.url;
        }

        if (thumbnail.height === 104) {
          self.littleThumbURL = thumbnail.url;
        }
      });
    }

    return {
      album: {

        createURI: function (user, bigThumbSize, littleThumbSize) {
          return getAlbumURI(user, bigThumbSize, littleThumbSize);
        },

        createModel: function (feedEntry) {
          return new Album(feedEntry);
        }
      },

      photo: {

      }
    };

  });